package com.example.webdome.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.webdome.enums.ValidationEnums;
import com.example.webdome.mapper.ValidationMapper;
import com.example.webdome.pojo.Emailnumber;
import com.example.webdome.pojo.Result;
import com.example.webdome.pojo.Validation;
import com.example.webdome.service.EmailnumberService;
import com.example.webdome.service.ValidationService;
import com.xiaoleilu.hutool.date.DateTime;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Date;

import static com.example.webdome.util.Emails.MAX_EMAIL_COUNT;
import static com.example.webdome.util.Emails.currentEmail;


@Service
@Slf4j
public class ValidationServiceImpl extends ServiceImpl<ValidationMapper, Validation> implements ValidationService {

    @Resource
    public ValidationMapper validationMapper;
    @Resource
    public ValidationService validationService;
    @Resource
    public EmailnumberService emailnumberService;
    @Resource
    JavaMailSender javaMailSender;

    @Override
    @Transactional
    public void saveCode(String email, String code, int type, DateTime offsiteMinute) {
        // 删除同类型的验证
        QueryWrapper<Validation> update = new QueryWrapper<>();
        update.eq("email", email);
        update.eq("type", type);
        validationMapper.selectOne(update);
        remove(update);
        Validation validation = new Validation();
        validation.setEmail(email);
        validation.setCode(code);
        validation.setType(type);
        validation.setTime(offsiteMinute);
        // 新增
        save(validation);
    }


    @Override
    @Transactional
    public Result sendRegisterEmail(String email) {
        LocalDate day = LocalDate.now();
        Date date = new Date();
        //查询同类型的邮件
        QueryWrapper<Validation> Wrapper = new QueryWrapper<>();
        Wrapper.eq("email", email);
        Wrapper.eq("type", ValidationEnums.REGISTER.getType());
        Wrapper.ge("time", date);
        Validation validation = validationMapper.selectOne(Wrapper);
        if (validation == null) {
            // 发送email
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("scj@atcumt.com");
            Date now = new Date();
            message.setSentDate(now);
            message.setSubject("注册验证");
            String registerCode = RandomUtil.randomNumbers(6);
            message.setText("【翔工作室】您的验证码为：" + registerCode + "有效期为2分钟。如果非本人操作，请忽略！");
            message.setTo(email);
            javaMailSender.send(message);
            log.info("发送成功");
            // 将数据存入数据库

            validationService.saveCode(email, registerCode, ValidationEnums.REGISTER.getType(), DateUtil.offsiteMinute(now, 2));
            // 统计发送次数并记录到数据库
            recordEmailCount(day);

            return Result.success("验证码已发送，请注意查收！");
        }
        return Result.failed("您的验证码还在有效期！无需再次获取！");
    }

    @Override
    @Transactional
    public Result sendFindEmail(String email) {
        LocalDate day = LocalDate.now();
        Date date = new Date();
        //查询同类型的邮件
        QueryWrapper<Validation> Wrapper = new QueryWrapper<>();
        Wrapper.eq("email", email);
        Wrapper.eq("type", ValidationEnums.FIND_PASSWORD.getType());
        Wrapper.ge("time", date);
        Validation validation = validationMapper.selectOne(Wrapper);
        if (validation == null) {
            // 发送email
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("scj@atcumt.com");
            Date now = new Date();
            message.setSentDate(now);
            message.setSubject("找回密码验证");
            String registerCode = RandomUtil.randomNumbers(6);
            message.setText("【翔工作室】您的验证码为：" + registerCode + "有效期为2分钟。如果非本人操作，请忽略！");
            message.setTo(email);
            javaMailSender.send(message);
            log.info("发送成功");
            // 将数据存入数据库

            validationService.saveCode(email, registerCode, ValidationEnums.FIND_PASSWORD.getType(), DateUtil.offsiteMinute(now, 2));
            // 统计发送次数并记录到数据库
            recordEmailCount(day);

            return Result.success("验证码已发送，请注意查收！");
        }
        return Result.failed("您的验证码还在有效期！无需再次获取！");
    }


    @Transactional
    void recordEmailCount(LocalDate now) {
        int currentCount = emailnumberService.getEmailCountByTypeAndDate(now);

        if (currentCount >= MAX_EMAIL_COUNT) {
            // 达到每日使用上限，返回提示
            // 这里可以根据需要返回合适的提示信息
            return;
        }

        Emailnumber emailnumber = new Emailnumber();
        emailnumber.setTime(now);

        if (currentCount == 0) {
            // 今日没有记录，添加新记录
            emailnumber.setNumber(1);
            emailnumberService.save(emailnumber);
        } else {
            // 今日已有记录，更新次数
            emailnumberService.update().setSql("number = number + 1").update();

        }
    }

}
